package com.kanshu.ksgb.fastread.doudou.module.bookcity.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.dl7.recycler.helper.RecyclerViewHelper;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.IGenrialMvpView;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.event.AdRefreshEvent;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.event.ScrollEvent;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.adapter.SelectedTopAdapter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.SelectedBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.view.AdSelectedHeaderLayout;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.view.MaleOrFemaleFooter;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by wcy on 18/5/14.
 */

public class AdMaleOrFemaleFragment extends BaseFragment implements IGenrialMvpView<BaseResult<List<SelectedBean>>>, BookCityCallListener {
    public static final String TYPE_SEX = "sex";
    @BindView(R.id.recyler_view_bottom)
    RecyclerView mRecylerViewBottom;
    @BindView(R.id.swipe_refresh)
    TwinklingRefreshLayout mSwipeRefresh;
    @BindView(R.id.scroll_to_top)
    ImageView mScrollToTop;
    Unbinder unbinder;
    // 区分男女
    int mType = Constants.BookCityTabType.TYPE_MALE;
    List<SelectedBean> mSelectedBeans = new ArrayList<>();
    SelectedTopAdapter mAdapter;
    MaleOrFemaleFooter mFooter;
    BookCityPresenter mPresenter;
    AdSelectedHeaderLayout mHeaderLayout;
    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new BookCityPresenter(lifeCyclerSubject);
        mPresenter.setMvpView(this);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_selected_layout, null);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void parseArguments() {
        if (getArguments() == null) {
            return;
        }
        mType = getArguments().getInt(TYPE_SEX);
    }

    public static AdMaleOrFemaleFragment newInstance(int type) {
        AdMaleOrFemaleFragment fragment = new AdMaleOrFemaleFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(TYPE_SEX, type);
        fragment.setArguments(bundle);
        return fragment;
    }


    private void init() {
        parseArguments();
        mFooter = new MaleOrFemaleFooter(getActivity());
        mAdapter = new SelectedTopAdapter(getActivity(), mSelectedBeans, mType);
        mHeaderLayout = new AdSelectedHeaderLayout(getActivity(), mType);
        mAdapter.addHeaderView(mHeaderLayout);
        SwipeRefreshHelper.initTwinklingRefresh(mSwipeRefresh, mFooter, new RefreshListenerAdapter() {
            @Override
            public void onPullingUp(TwinklingRefreshLayout refreshLayout, float fraction) {
                super.onPullingUp(refreshLayout, fraction);
                Log.d("wcy", "onPullingUp, fraction:" + fraction);
                mFooter.setTip(Math.abs(fraction) < 1.2 ? mType == Constants.BookCityTabType.TYPE_MALE ? "上拉跳转到女频" : "上拉跳转到男频" :
                        mType == Constants.BookCityTabType.TYPE_MALE ? "松手跳转到女频" : "松手跳转到男频");
            }

            @Override
            public void onPullUpReleasing(TwinklingRefreshLayout refreshLayout, float fraction) {
                super.onPullUpReleasing(refreshLayout, fraction);
                Log.d("wcy", "onPullUpReleasing fraction:" + fraction);
                mFooter.setTip(mType == Constants.BookCityTabType.TYPE_MALE ? "松手跳转到女频" : "松手跳转到男频");
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                refreshLayout.postDelayed(() -> {
                    int tabPos = mType == Constants.BookCityTabType.TYPE_MALE ? AdBookCityFragment.TYPE_TAB_FEMALE : AdBookCityFragment.TYPE_TAB_MALE;
                    refreshLayout.finishLoadmore();
                    mFooter.setTip(mType == Constants.BookCityTabType.TYPE_MALE ? "上拉跳转到女频" : "上拉跳转到男频");
                    ((AdBookCityFragment) getParentFragment()).switchTab(tabPos);
                    ScrollEvent event = new ScrollEvent();
                    event.type = tabPos;
                    EventBus.getDefault().post(event);

                }, 500);

            }

            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                mHeaderLayout.refresh();
                refreshSexSelectedInfos();
            }
        });
        mEmptyLayout.setRetryListener(new EmptyLayout.OnRetryListener() {
            @Override
            public void onRetry() {
                mHeaderLayout.refresh();
                refreshSexSelectedInfos();
            }
        });
        RecyclerViewHelper.initRecyclerViewV(getActivity(), mRecylerViewBottom, mAdapter);
        AdSelectedFragment.scrollToTop(mRecylerViewBottom, mScrollToTop, true,
                ((AdBookCityFragment) getParentFragment()).getTop(),
                ((AdBookCityFragment) getParentFragment()).getTabLayout(),
                ((AdBookCityFragment) getParentFragment()).getSearch(),
                ((AdBookCityFragment) getParentFragment()).getTopMask(),mType);
    }

    @Override
    protected void updateViews() {
        super.updateViews();
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
        mHeaderLayout.refresh();
        refreshSexSelectedInfos();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }

    private void refreshSexSelectedInfos() {
        mAdapter.reset();
        if (mType == Constants.BookCityTabType.TYPE_MALE) {
            mPresenter.getMaleSelectedInfos();
        } else {
            mPresenter.getFemaleSelectedInfos();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        if (mSwipeRefresh != null) {
            mSwipeRefresh.finishRefreshing();
        }
        mAdapter.clear();
        mPresenter.detachView();
    }

    @Override
    public void showLoading(String s) {

    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    @Override
    public void showContent(BaseResult<List<SelectedBean>> result) {
        DisplayUtils.visible(mRecylerViewBottom);
        mAdapter.setDatas(result.result.data);
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
        dismissLoading();
    }

    @Override
    public void showError(int errCode, String errDesc) {
        dismissLoading();
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, null);
        if (!NetUtils.isNetworkAvailable(getActivity())) {
            int status = EmptyLayout.STATUS_NO_NET;
            if (mEmptyLayout != null) {
                mEmptyLayout.setEmptyStatus(status);
            }

        }
        //showEmptyByCode(errCode, mEmptyLayout);
    }

    @Override
    public int getScrollDistance() {
        return Utils.getRecyclerScrollDistance(mRecylerViewBottom);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleScrollEvent(ScrollEvent event) {
        if (event.type == mType && mRecylerViewBottom != null) {
            mRecylerViewBottom.scrollToPosition(0);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleAdRefreshEvent(AdRefreshEvent event) {
        if (mAdapter != null) {
            mAdapter.reset();
        }
    }
}
